package com.siwei.mes.service.laboratory.factory.material.fine;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.entity.experiment.CheckBatchConfig;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.fineAggregate.FineAggregateNkhl;
import com.siwei.mes.entity.laboratory.DataDefaultUc;
import com.siwei.mes.entity.laboratory.fineAggregate.DataFineAggregateNkhl;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.entity.system.TestProjectSpecConfig;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.laboratory.FineLaboratoryMapper;
import com.siwei.mes.mapper.laboratory.UploadLaboratoryMapper;
import com.siwei.mes.service.laboratory.factory.LaboratoryAbstractService;
import com.siwei.mes.service.laboratory.factory.entity.LaboratoryDownloadVo;
import com.siwei.mes.service.laboratory.factory.material.MaterialLaboratoryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 细骨料-泥块含量
 *
 * @Description: 细骨料-泥块含量
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/29 21:30
 */
@Service
public class FineNkhlFactory extends LaboratoryAbstractService implements MaterialLaboratoryFactory {
    private static final Logger log = LoggerFactory.getLogger("laboratory");

    @Resource
    private UploadLaboratoryMapper uploadLaboratoryMapper;
    @Resource
    private FineLaboratoryMapper fineLaboratoryMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;

    private final TestProjectEnum testProjectEnum = TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_NKHL;

    @Override
    public void processUpload(JSONObject objJson, String sampleNo, Experiment experiment, List<CheckBatchConfig> batchConfigList, List<TestProjectInfo> testProjectInfoList, List<TestProjectSpecConfig> testProjectSpecConfigList, ExperimentDetail detail, String samId) {
        log.info("开始上传到协会数据库：【细骨料-{}】", testProjectEnum.getName());
        //将json转成对象
        FineAggregateNkhl fineNkhl = objJson.toJavaObject(FineAggregateNkhl.class);
        if (fineNkhl == null) {
            log.info("细骨料-【{}】数据为空，跳过上传！objJson：{}", testProjectEnum.getName(), objJson);
            return;
        }
        DataFineAggregateNkhl dataFineNkhl = new DataFineAggregateNkhl();

        List<FineAggregateNkhl.HnkInfo> hnkInfo = fineNkhl.getHnkInfo();
        if (CollectionUtil.isNotEmpty(hnkInfo)) {
            if (!hnkInfo.isEmpty()) {
                FineAggregateNkhl.HnkInfo hnkInfoOne = hnkInfo.get(0);
                if (hnkInfoOne != null) {
                    dataFineNkhl.setS1(NullUtils.ifNull(hnkInfoOne.getHqsyzl()));
                    dataFineNkhl.setS2(NullUtils.ifNull(hnkInfoOne.getHhsyzl()));
                    dataFineNkhl.setS3(NullUtils.ifNull(hnkInfoOne.getHnl()));
                }
            }
            if (hnkInfo.size() > 1) {
                FineAggregateNkhl.HnkInfo hnkInfoTwo = hnkInfo.get(1);
                if (hnkInfoTwo != null) {
                    dataFineNkhl.setS4(NullUtils.ifNull(hnkInfoTwo.getHqsyzl()));
                    dataFineNkhl.setS5(NullUtils.ifNull(hnkInfoTwo.getHhsyzl()));
                    dataFineNkhl.setS6(NullUtils.ifNull(hnkInfoTwo.getHnl()));
                }
            }
        }
        dataFineNkhl.setS7(NullUtils.ifNull(fineNkhl.getPjz()));

        //设置公共属性
        super.setCommonProperties(sampleNo, experiment, dataFineNkhl, "骨料检测室", fineNkhl.getJcrq(), detail);
        //李总确认 sampleID = 110314，泥块含量插入 DATA_JGCL_SS_SSHLSZNKHL表
        if("110314".equals(samId)){
            //根据样品编码查询细骨料泥块含量
            Map<String, Object> data_jgcl_ss_sznkhlbBySampleNo = fineLaboratoryMapper.findDATA_JGCL_SS_SSHLSZNKHLBySampleNo(sampleNo);
            //查询没值说明需要  新增细骨料泥块含量
            if (data_jgcl_ss_sznkhlbBySampleNo == null) {
                fineLaboratoryMapper.addDATA_JGCL_SS_SSHLSZNKHL(dataFineNkhl);
            } else {
                //修改细骨料泥块含量
                fineLaboratoryMapper.updateDATA_JGCL_SS_SSHLSZNKHL(dataFineNkhl);
            }
        }else{
            //根据样品编码查询细骨料泥块含量
            Map<String, Object> data_jgcl_ss_sznkhlbBySampleNo = fineLaboratoryMapper.findDATA_JGCL_SS_SZNKHLBySampleNo(sampleNo);
            //查询没值说明需要  新增细骨料泥块含量
            if (data_jgcl_ss_sznkhlbBySampleNo == null) {
                fineLaboratoryMapper.addDATA_JGCL_SS_SZNKHL(dataFineNkhl);
            } else {
                //修改细骨料泥块含量
                fineLaboratoryMapper.updateDATA_JGCL_SS_SZNKHL(dataFineNkhl);
            }
        }

        //赋值dateDefalutUC
        //存储协会需要做的项目集合
        Set<String> set = new HashSet<>();

        for (TestProjectInfo testProjectInfo : testProjectInfoList) {
            if (detail.getTestProjectCode() != null && testProjectInfo.getTestCode() != null && testProjectInfo.getTestCode().equals(detail.getTestProjectCode())) {
                if (testProjectInfo.getParameterName() != null && !testProjectInfo.getParameterName().isEmpty()) {
                    //添加进协会需要做的项目集合
                    set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                }
            }
        }

        for (String str : set) {
            DataDefaultUc defaultUc = new DataDefaultUc();

            Map<String, Object> itemParameter = uploadLaboratoryMapper.findItemParameter(str, samId);

            if (itemParameter == null || itemParameter.get("ParameterID") == null) {
                log.error("未查询到对应的材料：value = " + str + "SampleID =" + samId);
                continue;
            }
            String parameterID = itemParameter.get("ParameterID").toString();

            String jcrq = fineNkhl.getJcrq();

            defaultUc.setConclusion(fineNkhl.getDxjl());
            defaultUc.setUcResultValue(fineNkhl.getDxjl());
            defaultUc.setUcTestValue(fineNkhl.getPjz());


            for (CheckBatchConfig projectInfo : batchConfigList) {
                if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_NKHL.getCode())) {
                    defaultUc.setUcUnit(NullUtils.ifNull(projectInfo.getCheckValueUnit()));
                }
            }


            //根据物料信息设置判断配置
            for (TestProjectSpecConfig test : testProjectSpecConfigList) {
                if (TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_NKHL.getCode().equals(test.getTestProjectCode())) {
                    if (experiment.getMaterialsName() != null && experiment.getMaterialsSpecs() != null && experiment.getMaterialsName().equals(test.getMaterialsName()) && experiment.getMaterialsSpecs().equals(test.getMaterialsSpec())) {
                        String json = test.getObjJson();
                        super.setUcStandardValue(defaultUc, json, "nkhl");
                    }
                }
            }

            //赋值
            super.setDefUc(defaultUc, experiment, "骨料检测室", sampleNo, jcrq, detail);

            defaultUc.setUcParameterID(parameterID);//项目id

            //新增或修改DataDefaultUc
            super.insertOrUpdateDataDefaultUc(sampleNo, parameterID, defaultUc);
        }
    }

    @Override
    public LaboratoryDownloadVo processDownload(String sampleNo, Experiment experiment, ExperimentDetail detail, Map<String, String> parameterMap, String samId, List<TestProjectInfo> testProjectInfoList) {
        log.info("开始下载协数据到品控：【细骨料-{}】", testProjectEnum.getName());
        JSONObject objJson = detail.getObjJson();
        //将json转成对象
        FineAggregateNkhl fineAggregateNkhl = objJson.toJavaObject(FineAggregateNkhl.class);
        if (fineAggregateNkhl == null) {
            log.info("细骨料-【{}】数据为空，跳过下载！objJson：{}", testProjectEnum.getName(), objJson);
            return null;
        }
        //根据样品编码查询细骨料泥块含量
        Map<String, Object> data = null;
        //李总确认 sampleID = 110314，泥块含量插入 DATA_JGCL_SS_SSHLSZNKHL表
        if("110314".equals(samId)){
            data = fineLaboratoryMapper.findDATA_JGCL_SS_SSHLSZNKHLBySampleNo(sampleNo);
        }else{
            data = fineLaboratoryMapper.findDATA_JGCL_SS_SZNKHLBySampleNo(sampleNo);
        }
        if (data == null) {
            log.info("根据样品编码查询细骨料泥块含量为空，跳过下载！sampleNo：{}", sampleNo);
            return null;
        }
        FineAggregateNkhl.setValue(fineAggregateNkhl, data);
        //对象转json
        JSONObject jsonObject = JsonUtils.beanToObject(fineAggregateNkhl);

        //重新赋值
        detail.setObjJson(jsonObject);

        detail.setEquipment(NullUtils.ifNull(data.get("Equipment")));
        detail.setTemperature(NullUtils.ifNull(data.get("Temperature")));
        detail.setHumidness(NullUtils.ifNull(data.get("Humidity")));
        detail.setExperimentGist(NullUtils.ifNull(data.get("DetectonRuleCode")));
        detail.setJudgeGist(NullUtils.ifNull(data.get("AccessRuleCode")));

        experimentDetailMapper.updateByPrimaryKeySelective(detail);
        return new LaboratoryDownloadVo().setEquipment(detail.getEquipment())
                .setJudgeGist(detail.getJudgeGist())
                .setExperimentGist(detail.getExperimentGist())
                .setTemperature(detail.getTemperature())
                .setHumidness(detail.getHumidness());
    }
}
